const { ipcMain } = require("electron");

const { uIOhook, UiohookKey } = require('uiohook-napi')
const { createWin } = require("./share");
const path = require("path");


function getKeyByValue(obj, value) {
    for (const [key, val] of Object.entries(obj)) {
        if (val === value) {
            return key;
        }
        
    }
    return null;
}

const createHotkviewWin = () => {
    const hotkviewWin = createWin({
        width: 400,
        height: 100,
        webPreferences: {
            nodeIntegration: true, // 允许预加载js文件使用require模块
            preload: path.join(__dirname, "../src/view/hotkey/preload.js"),
        },
        transparent: true
    }, "./src/view/hotkey/index.html");
    // hotkviewWin.webContents.openDevTools()
    return hotkviewWin;
};
const createIpcHotk = () => {
    let hotkvWin
    const pressedKeys = new Set();

    
    ipcMain.on("open-hotkeyview", () => {
        hotkvWin = createHotkviewWin();
        // 设置窗口在最顶层
        hotkvWin.setAlwaysOnTop(true);

        uIOhook.on('keydown', (e) => {
            if (!pressedKeys.has(e.keycode)) {
                pressedKeys.add(e.keycode);
                const keysArr = Array.from(pressedKeys).map(keycode => getKeyByValue(UiohookKey, keycode)).filter(key => key !== null);
                hotkvWin.webContents.send('key-show', keysArr);
            }
        })
        uIOhook.on('keyup', (e) => {
            pressedKeys.delete(e.keycode);
        })
        uIOhook.start()

        // 监听窗口关闭
        hotkvWin.on('closed', () => {
            uIOhook.stop()
            hotkvWin = null
        })
    });

    ipcMain.on("close-hotkeyview", () => {
        hotkvWin.close();
    });
    
}

module.exports = {
    createIpcHotk
}